package com.im.service.service.impl;

import cn.hutool.core.text.StrPool;
import com.im.service.common.ServiceException;
import com.im.service.common.UploadResult;
import com.im.service.service.MinioService;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * @author liuzhiqiang
 */

@Service
@Slf4j
public class MinioServiceImpl implements MinioService {

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucket}")
    private String bucket;

    @Value("${minio.url}")
    private String url;

    @Override
    public UploadResult upload(MultipartFile file) {
        try {
            // 文件夹命名
            String day = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);
            String prefix = LocalTime.now().format(DateTimeFormatter.ofPattern("HHmmss"));
            String object = new StringBuilder(day).append(StrPool.SLASH).append(prefix).append(StrPool.DASHED).append(file.getOriginalFilename()).toString();
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(bucket)
                    .object(object)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build();

            minioClient.putObject(putObjectArgs);
            String networkUrl = new StringBuilder(this.url).append(StrPool.SLASH).append(bucket).append(StrPool.SLASH).append(object).toString();
            log.info("网路地址: {}", networkUrl);
            UploadResult uploadResult = new UploadResult();
            uploadResult.setUrl(networkUrl);
            uploadResult.setFileName(object);
            return uploadResult;
        } catch (Exception e) {
            log.error("Upload failed:", e);
            throw new ServiceException("上传失败");
        }
    }

    @Override
    public InputStream getInputStream(String url) {
        String object = url.replaceAll(new StringBuilder(this.url).append(StrPool.SLASH).append(bucket).append(StrPool.SLASH).toString(), "");
        GetObjectArgs getObjectArgs = GetObjectArgs.builder().bucket(bucket).object(object).build();
        try {
            InputStream inputStream = minioClient.getObject(getObjectArgs);
            return inputStream;
        } catch (Exception e) {
            log.error("获取文件流失败", e);
            throw new ServiceException("Error getting object");
        }
    }
}
